package com.ruicar.afs.cloud.afscase.channel.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.common.Constants;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelQuotaInfo;
import com.ruicar.afs.cloud.afscase.channel.feign.ChannelFeignService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelQuotaInfoService;
import com.ruicar.afs.cloud.afscase.channel.utils.CaseConfig;
import com.ruicar.afs.cloud.common.job.core.biz.model.ReturnT;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJob;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJobHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author sangjian
 */
@Slf4j
@Component
@RestController
@AllArgsConstructor
@AfsJob
public class ChannelQuotaTask {
    /**
     * 风控信息表
     */
    private final ChannelBaseInfoService channelBaseInfoService;
    private final ChannelQuotaInfoService channelQuotaInfoService;
    private final ChannelFeignService channelFeignService;
    private final CaseConfig caseConfig;


    @AfsJobHandler(value = "channelQuotaTask")
    public ReturnT<String> channelQuotaTask(String param){
        log.info("启动定时任务【渠道额度重算】");
        //获取当前日期时间
        Long dayTime = new Date().getTime();
        List<ChannelQuotaInfo> totalChannelQuotaInfoList = new ArrayList<>();
        //Step1：查询额度信息表数据并更新数据库
        List<ChannelQuotaInfo> list = channelQuotaInfoService.list();

        if(list.size() > 0){
            for (ChannelQuotaInfo quotaInfo : list){
                if(quotaInfo.getValidityTermEnd() != null){
                    long time = DateUtil.endOfDay(quotaInfo.getValidityTermEnd()).getTime();
                    if (dayTime > time){
                        BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                        if(tempQuota.compareTo(BigDecimal.ZERO) != 0 ){
                            //剩余额度减掉临时额度
                            quotaInfo.setSurplusQuota(quotaInfo.getSurplusQuota()==null?BigDecimal.ZERO:quotaInfo.getSurplusQuota().subtract(tempQuota).setScale(2, BigDecimal.ROUND_HALF_UP));
                            //临时额度归零
                            quotaInfo.setTempQuota(BigDecimal.ZERO);
                            //临时额度到期日归零
                            quotaInfo.setValidityTermEnd(null);
                            channelQuotaInfoService.updateById(quotaInfo);
                            totalChannelQuotaInfoList.add(quotaInfo);
                        }
                    }
                }
            }
        }
        if(totalChannelQuotaInfoList.size() > 0){
            //请求头
            Map<String, String> headers = new HashMap<>();
            //接口返回结果
            headers.put("clientId", caseConfig.getChannelClientId());
            headers.put("clientSecret", caseConfig.getChannelClientSecret());
            channelFeignService.updateChannelQuota(totalChannelQuotaInfoList, headers);
        }

        //获取所有已启用的渠道
        List<Long> newCarchannelIds = new ArrayList<>();
        List<ChannelBaseInfo> newCarChannel = channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                .eq(ChannelBaseInfo::getChannelStatus, Constants.ENABLED)
                .eq(ChannelBaseInfo::getChannelType, Constants.CHANNEL)
        );
        if(newCarChannel.size() > 0){
            for (ChannelBaseInfo baseInfo : newCarChannel){
                newCarchannelIds.add(baseInfo.getId());
            }
        }

        //开始重算
        channelQuotaInfoService.quotaRecompute(newCarchannelIds,Constants.BUSINESS_TYPE_NEW_CAR);

        List<Long> oldCarchannelIds = new ArrayList<>();
        List<ChannelBaseInfo> oldCarChannel = channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                .eq(ChannelBaseInfo::getChannelStatusOldCar, Constants.ENABLED)
                .eq(ChannelBaseInfo::getChannelType, Constants.CHANNEL)
        );

        if(oldCarChannel.size() > 0){
            for (ChannelBaseInfo baseInfo : oldCarChannel){
                oldCarchannelIds.add(baseInfo.getId());
            }
        }
        channelQuotaInfoService.quotaRecompute(oldCarchannelIds,Constants.BUSINESS_TYPE_OLD_CAR);
        return ReturnT.SUCCESS;
    }

}
